package com.zhixue.study.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhixue.content.model.po.CoursePublish;
import com.zhixue.exception.ZhixuePlusException;
import com.zhixue.study.feignclient.ContentServiceClient;
import com.zhixue.study.mapper.*;
import com.zhixue.study.model.dto.*;
import com.zhixue.study.model.po.*;
import com.zhixue.study.service.MyCourseTablesService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * @Auther: 李 力
 * @Date: 2025/5/15
 * @Description: com.zhixue.study.service.impl
 * @version: 1.0
 */
@Service
public class CourseTablesServiceImpl extends ServiceImpl<XcCourseTablesMapper, XcCourseTables> implements MyCourseTablesService {

    @Autowired
    private XcChooseCourseMapper chooseCourseMapper;

    @Autowired
    private XcCourseTablesMapper tablesMapper;

    @Autowired
    private ContentServiceClient contentServiceClient;

    @Autowired
    private CourseTablesServiceImpl courseTablesService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public XcChooseCourseDto addChooseCourse(String userId, Long courseId) {
        //远程调用内容管理服务查询课程
        if (StringUtils.isEmpty(userId) || courseId == null) {
            throw new ZhixuePlusException("参数为空");
        }
        //先查询有无记录
        CoursePublish coursepublish = contentServiceClient.getCoursepublish(courseId);
        if (coursepublish == null) {
            throw new ZhixuePlusException("没有对应的课程信息");
        }
        //收费规则
        String charge = coursepublish.getCharge();
        XcChooseCourse xcChooseCourse = null;
        if ("201000".equals(charge)) {
            //免费 :向选课记录表，我的课程表写数据
            //选课记录
            xcChooseCourse = courseTablesService.addFreeCoruse(userId, coursepublish);
            //我的课程表
            courseTablesService.addCourseTabls(xcChooseCourse);
        } else {
            //收费: 向选课记录表写数据
            xcChooseCourse = courseTablesService.addChargeCoruse(userId, coursepublish);
        }
        //判断学生的学习资格
        XcCourseTablesDto tablesDto = getLearningStatus(userId, courseId);
        XcChooseCourseDto courseDto = new XcChooseCourseDto();
        BeanUtils.copyProperties(xcChooseCourse, courseDto);
        courseDto.setLearnStatus(tablesDto.getLearnStatus());
        return courseDto;
    }

    //添加免费课程,免费课程加入选课记录表、我的课程表
    //选课记录表
    public XcChooseCourse addFreeCoruse(String userId, CoursePublish coursepublish) {
        //查询选课记录表是否存在免费的且选课成功的订单
        LambdaQueryWrapper<XcChooseCourse> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper = queryWrapper.eq(XcChooseCourse::getUserId, userId)
                .eq(XcChooseCourse::getCourseId, coursepublish.getId())
                .eq(XcChooseCourse::getOrderType, "700001")//免费课程
                .eq(XcChooseCourse::getStatus, "701001");//选课成功
        XcChooseCourse xcChooseCourse = chooseCourseMapper.selectOne(queryWrapper);
        //存在
        if (xcChooseCourse != null) {
            return xcChooseCourse;
        }
        //不存在
        //向选课记录表写数据
        XcChooseCourse chooseCourseNew = new XcChooseCourseDto();
        chooseCourseNew.setCourseId(coursepublish.getId());
        chooseCourseNew.setCourseName(coursepublish.getName());
        chooseCourseNew.setCoursePrice(0f);//免费课程价格为0
        chooseCourseNew.setUserId(userId);
        chooseCourseNew.setCompanyId(coursepublish.getCompanyId());
        chooseCourseNew.setOrderType("700001");//免费课程
        chooseCourseNew.setCreateDate(new Date());
        chooseCourseNew.setStatus("701001");//选课成功
        chooseCourseNew.setValidDays(365);//免费课程默认365
        chooseCourseNew.setValidtimeStart(new Date());
        chooseCourseNew.setValidtimeEnd(LocalDateTime.now().plusDays(365));
        int insert = chooseCourseMapper.insert(chooseCourseNew);
        if (insert <= 0) {
            throw new ZhixuePlusException("添加选课记录失败");
        }
        return chooseCourseNew;
    }

    //添加到我的课程表
    public XcCourseTables addCourseTabls(XcChooseCourse xcChooseCourse) {
        //选课记录完成且未过期可以添加课程到课程表
        String status = xcChooseCourse.getStatus();
        if (!"701001".equals(status)) {
            throw new ZhixuePlusException("选课未成功，无法添加到课程表");
        }
        //查重
        LambdaQueryWrapper<XcCourseTables> wrapper = new LambdaQueryWrapper<>();
        wrapper = wrapper.eq(XcCourseTables::getUserId, xcChooseCourse.getUserId())
                .eq(XcCourseTables::getCourseId, xcChooseCourse.getCourseId());
        XcCourseTables xcCourseTables = tablesMapper.selectOne(wrapper);
        if (xcCourseTables != null) {
            return xcCourseTables;
        }
        XcCourseTables xcCourseTablesNew = new XcCourseTables();
        xcCourseTablesNew.setChooseCourseId(xcChooseCourse.getId());
        xcCourseTablesNew.setUserId(xcChooseCourse.getUserId());
        xcCourseTablesNew.setCourseId(xcChooseCourse.getCourseId());
        xcCourseTablesNew.setCompanyId(xcChooseCourse.getCompanyId());
        xcCourseTablesNew.setCourseName(xcChooseCourse.getCourseName());
        xcCourseTablesNew.setCreateDate(new Date());
        xcCourseTablesNew.setValidtimeStart(xcChooseCourse.getValidtimeStart());
        xcCourseTablesNew.setValidtimeEnd(xcChooseCourse.getValidtimeEnd());
        xcCourseTablesNew.setCourseType(xcChooseCourse.getOrderType());
        tablesMapper.insert(xcCourseTablesNew);
        return xcCourseTablesNew;
    }

    //添加收费课程
    public XcChooseCourse addChargeCoruse(String userId, CoursePublish coursepublish) {
        LambdaQueryWrapper<XcChooseCourse> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper = queryWrapper.eq(XcChooseCourse::getUserId, userId)
                .eq(XcChooseCourse::getCourseId, coursepublish.getId())
                .eq(XcChooseCourse::getOrderType, "700002")//收费课程
                .eq(XcChooseCourse::getStatus, "701002");//待支付
        XcChooseCourse xcChooseCourse = chooseCourseMapper.selectOne(queryWrapper);
        //存在
        if (xcChooseCourse != null) {
            return xcChooseCourse;
        }
        //不存在
        //向选课记录表写数据
        xcChooseCourse = new XcChooseCourseDto();
        xcChooseCourse.setCourseId(coursepublish.getId());
        xcChooseCourse.setCourseName(coursepublish.getName());
        xcChooseCourse.setCoursePrice(coursepublish.getPrice());
        xcChooseCourse.setUserId(userId);
        xcChooseCourse.setCompanyId(coursepublish.getCompanyId());
        xcChooseCourse.setOrderType("700002");//收费课程
        xcChooseCourse.setCreateDate(new Date());
        xcChooseCourse.setStatus("701002");//待支付
        xcChooseCourse.setValidDays(coursepublish.getValidDays());
        xcChooseCourse.setValidtimeStart(new Date());
        xcChooseCourse.setValidtimeEnd(LocalDateTime.now().plusDays(coursepublish.getValidDays()));
        int insert = chooseCourseMapper.insert(xcChooseCourse);
        if (insert <= 0) {
            throw new ZhixuePlusException("添加选课记录失败");
        }
        return xcChooseCourse;
    }

    /*
     * [{"code":"702001","desc":"正常学习"},{"code":"702002","desc":"没有选课或选课后没有支付"},{"code":"702003","desc":"已过期需要申请续期或重新支付"}]
     * */
    @Override
    public XcCourseTablesDto getLearningStatus(String userId, Long courseId) {
        XcCourseTablesDto tablesDto = new XcCourseTablesDto();
        //查询我的课程表
        LambdaQueryWrapper<XcCourseTables> wrapper = new LambdaQueryWrapper<>();
        wrapper = wrapper.eq(XcCourseTables::getUserId, userId)
                .eq(XcCourseTables::getCourseId, courseId);
        XcCourseTables xcCourseTables = tablesMapper.selectOne(wrapper);
        //如果查不到没有选课不具备资格
        if (xcCourseTables == null) {
            tablesDto.setLearnStatus("702002");
            return tablesDto;
        }
        //如果查到了，判断是否过期
        boolean before = xcCourseTables.getValidtimeEnd().isBefore(LocalDateTime.now());
        BeanUtils.copyProperties(xcCourseTables, tablesDto);
        if (before) {
            //过期了不能继续学习
            tablesDto.setLearnStatus("702003");
            return tablesDto;
        } else {
            tablesDto.setLearnStatus("702001");
            return tablesDto;
        }
    }

    //保存选课成功
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveChooseCourseStauts(String choosecourseId) {
        XcChooseCourse xcChooseCourse = chooseCourseMapper.selectById(choosecourseId);
        if (xcChooseCourse == null) {
            return false;
        }
        //状态
        String status = xcChooseCourse.getStatus();
        if ("701002".equals(status)) {
            //未支付,更新选课记录状态，向我的课程表插入记录
            xcChooseCourse.setStatus("701001");
            int i = chooseCourseMapper.updateById(xcChooseCourse);
            if (i <= 0) {
                throw new ZhixuePlusException("添加选课记录失败");
            }
            XcCourseTables xcCourseTables = addCourseTabls(xcChooseCourse);
            return true;
        }
        return false;
    }
}
